package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utils.XmlParser;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import app.cloudstringers.Completed;
import app.cloudstringers.R;
import define.API;
import define.Constants;
import define.Key;
import define.SharedPreference;

public class SaveMemoInfoAsync extends AsyncTask<String, Void, Boolean> {
	private static final String TAG = SaveMemoInfoAsync.class.getSimpleName();

	// All static variables
	private static final String KEY_GLOBAL_ID = "GLOBAL_ID";
	private static final String KEY_USER_ID = "USER_ID";

	private String ID = null;
	private String NEW_MEMO = null;
	private String NEW_TITLE = null;
	private String UPLOAD_ID = null;

	/**
	 * View section
	 */
	private AlertDialog.Builder mAdConnection;
	private AlertDialog.Builder mAdSave;

	/**
	 * The Other Tools
	 */
	private Context context;
	private SharedPreferences.Editor mSpEditor;
	private SharedPreferences mSpSettings;
	private XmlParser mXMLParser;

	public SaveMemoInfoAsync(Context context) {
		this.context = context;

		initialAlertDialogs();

		// Get stored data from shared preferences
		mSpSettings = context.getSharedPreferences(SharedPreference.PREFS,
				Context.MODE_PRIVATE);
		mSpEditor = mSpSettings.edit();
	}

	@Override
	protected Boolean doInBackground(String... params) {
		// Get data
		ID = params[0];
		NEW_MEMO = params[1];
		NEW_TITLE = params[2];
		UPLOAD_ID = params[3];

		try {
			HttpClient mHttpClient = new DefaultHttpClient();
			HttpPost mHttpPost = new HttpPost(API.UPDATE_TITLE);

			List<NameValuePair> mNameValuePairs = new ArrayList<NameValuePair>(
					2);

			mNameValuePairs.add(new BasicNameValuePair(Key.KEY_GLOBAL_ID, ID));
			mNameValuePairs.add(new BasicNameValuePair(Key.KEY_UPLOAD_ID,
					UPLOAD_ID));
			mNameValuePairs
					.add(new BasicNameValuePair(Key.KEY_TITLE, NEW_TITLE));

			mHttpPost.setEntity(new UrlEncodedFormEntity(mNameValuePairs));
			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			mXMLParser = new XmlParser();
			Document mDocument = mXMLParser.getDomElement(XML);

			NodeList mNodeList = mDocument.getElementsByTagName(KEY_USER_ID);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) mNodeList.item(i);
					ID = mXMLParser.getValue(element, KEY_GLOBAL_ID);
				}
			}

			mSpEditor.putString(SharedPreference.PREFS_KEY_GLOBAL_ID, ID);
			mSpEditor.commit();

			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Retrieve data relatively
		try {
			HttpClient mHttpClient = new DefaultHttpClient();
			HttpPost mHttpPost = new HttpPost(API.UPDATE_MEMO);

			List<NameValuePair> mNameValuePairs = new ArrayList<NameValuePair>(
					2);

			mNameValuePairs.add(new BasicNameValuePair(Key.KEY_GLOBAL_ID, ID));
			mNameValuePairs.add(new BasicNameValuePair(Key.KEY_UPLOAD_ID,
					UPLOAD_ID));
			mNameValuePairs.add(new BasicNameValuePair(Key.KEY_MEMO, NEW_MEMO));

			mHttpPost.setEntity(new UrlEncodedFormEntity(mNameValuePairs));
			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();
			String XML = EntityUtils.toString(mHttpEntity);

			mXMLParser = new XmlParser();
			Document mDocument = mXMLParser.getDomElement(XML);

			NodeList mNodeList = mDocument.getElementsByTagName(KEY_USER_ID);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) mNodeList.item(i);
					ID = mXMLParser.getValue(element, KEY_GLOBAL_ID);
				}
			}

			Log.i(TAG, "Content : " + mNameValuePairs.toString());

			mSpEditor.putString(SharedPreference.PREFS_KEY_GLOBAL_ID, ID);
			mSpEditor.commit();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// show progress dialog
		Constants.utils.showProgressDialog();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if (!result) {
			Constants.utils.showConnectionTimeoutDialog(context,
					Completed.class);
		} else {
			// Show save dialog
			mAdSave.show();

			// hide progress dialog
			Constants.utils.hideProgressDialog();

			// Need refresh Completed Tab in here
			new CompletedAsync(context).execute(ID);
		}

		// hide progress dialog
		Constants.utils.hideProgressDialog();
	}

	/**
	 * Initial methods
	 */
	private void initialAlertDialogs() {
		mAdConnection = new AlertDialog.Builder(context);
		mAdConnection.setTitle(context
				.getString(R.string.title_failed_connection));
		mAdConnection.setIcon(R.drawable.ibtn_error_normal);
		mAdConnection.setCancelable(false);
		mAdConnection.setMessage(context
				.getString(R.string.content_failed_server_connection));
		mAdConnection.setPositiveButton(R.string.try_again,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
					}
				});
		mAdConnection.setNegativeButton(R.string.quit,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});

		mAdSave = new AlertDialog.Builder(context);
		mAdSave.setMessage(context.getString(R.string.save));
		mAdSave.setCancelable(false);
		mAdSave.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
	}
}
